import React, { useState } from 'react';
import { Typography, Card, Row, Col, Table, Tag, Progress, Alert, Space, Button } from 'antd';
import { MonitorOutlined, WarningOutlined, CheckCircleOutlined, ClockCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;

interface CertificateStatus {
  id: string;
  domain: string;
  status: 'healthy' | 'warning' | 'expired' | 'error';
  daysUntilExpiry: number;
  lastCheck: string;
  issuer: string;
  autoRenew: boolean;
}

const CertificateMonitor: React.FC = () => {
  // 模拟监控数据
  const [monitorData] = useState<CertificateStatus[]>([
    {
      id: '1',
      domain: 'example.com',
      status: 'healthy',
      daysUntilExpiry: 65,
      lastCheck: '2024-01-15 10:30:00',
      issuer: "Let's Encrypt",
      autoRenew: true
    },
    {
      id: '2',
      domain: 'api.example.com',
      status: 'warning',
      daysUntilExpiry: 15,
      lastCheck: '2024-01-15 10:30:00',
      issuer: 'ZeroSSL',
      autoRenew: false
    },
    {
      id: '3',
      domain: 'old.example.com',
      status: 'expired',
      daysUntilExpiry: -5,
      lastCheck: '2024-01-15 10:30:00',
      issuer: '阿里云SSL',
      autoRenew: false
    },
    {
      id: '4',
      domain: 'test.example.com',
      status: 'error',
      daysUntilExpiry: 30,
      lastCheck: '2024-01-15 09:15:00',
      issuer: "Let's Encrypt",
      autoRenew: true
    }
  ]);

  const getStatusConfig = (status: CertificateStatus['status']) => {
    const configs = {
      healthy: { color: 'success', text: '正常', icon: <CheckCircleOutlined /> },
      warning: { color: 'warning', text: '即将过期', icon: <WarningOutlined /> },
      expired: { color: 'error', text: '已过期', icon: <ClockCircleOutlined /> },
      error: { color: 'error', text: '监控异常', icon: <WarningOutlined /> }
    };
    return configs[status];
  };

  const getHealthScore = () => {
    const total = monitorData.length;
    const healthy = monitorData.filter(cert => cert.status === 'healthy').length;
    return Math.round((healthy / total) * 100);
  };

  const stats = {
    total: monitorData.length,
    healthy: monitorData.filter(cert => cert.status === 'healthy').length,
    warning: monitorData.filter(cert => cert.status === 'warning').length,
    expired: monitorData.filter(cert => cert.status === 'expired').length,
    error: monitorData.filter(cert => cert.status === 'error').length,
  };

  const columns: ColumnsType<CertificateStatus> = [
    {
      title: '域名',
      dataIndex: 'domain',
      key: 'domain',
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: CertificateStatus['status']) => {
        const config = getStatusConfig(status);
        return (
          <Space>
            {config.icon}
            <Tag color={config.color}>{config.text}</Tag>
          </Space>
        );
      },
    },
    {
      title: '过期时间',
      dataIndex: 'daysUntilExpiry',
      key: 'daysUntilExpiry',
      render: (days: number) => (
        <Text type={days < 30 ? 'danger' : days < 60 ? 'warning' : 'secondary'}>
          {days > 0 ? `${days}天后过期` : `已过期${Math.abs(days)}天`}
        </Text>
      ),
      sorter: (a, b) => a.daysUntilExpiry - b.daysUntilExpiry,
    },
    {
      title: '颁发机构',
      dataIndex: 'issuer',
      key: 'issuer',
    },
    {
      title: '自动续期',
      dataIndex: 'autoRenew',
      key: 'autoRenew',
      render: (autoRenew: boolean) => (
        <Tag color={autoRenew ? 'blue' : 'default'}>
          {autoRenew ? '已启用' : '已禁用'}
        </Tag>
      ),
    },
    {
      title: '最后检查',
      dataIndex: 'lastCheck',
      key: 'lastCheck',
      render: (time: string) => <Text type="secondary">{time}</Text>,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small">
            详情
          </Button>
          {(record.status === 'warning' || record.status === 'expired') && (
            <Button type="link" size="small">
              续期
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '24px' }}>
        <Title level={2} style={{ margin: 0, marginBottom: '8px' }}>
          <MonitorOutlined style={{ marginRight: '8px', color: '#722ed1' }} />
          证书监控
        </Title>
        <Text type="secondary">
          实时监控SSL证书状态，提供过期提醒和自动续期
        </Text>
      </div>

      {/* 概览统计 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#1890ff', marginBottom: '8px' }}>
                {stats.total}
              </div>
              <Text type="secondary">监控总数</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#52c41a', marginBottom: '8px' }}>
                {stats.healthy}
              </div>
              <Text type="secondary">正常</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#fa8c16', marginBottom: '8px' }}>
                {stats.warning}
              </div>
              <Text type="secondary">即将过期</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#ff4d4f', marginBottom: '8px' }}>
                {stats.expired + stats.error}
              </div>
              <Text type="secondary">异常</Text>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 健康度评分 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row align="middle">
          <Col span={12}>
            <div>
              <Title level={4} style={{ marginBottom: '8px' }}>
                证书健康度评分
              </Title>
              <Text type="secondary">
                基于证书状态和过期时间的综合评分
              </Text>
            </div>
          </Col>
          <Col span={12}>
            <div style={{ textAlign: 'right' }}>
              <Progress
                type="dashboard"
                percent={getHealthScore()}
                format={(percent) => `${percent}分`}
                strokeColor={{
                  '0%': '#ff4d4f',
                  '50%': '#fa8c16',
                  '100%': '#52c41a',
                }}
              />
            </div>
          </Col>
        </Row>
      </Card>

      {/* 预警信息 */}
      {(stats.warning > 0 || stats.expired > 0 || stats.error > 0) && (
        <Alert
          message="发现证书异常"
          description={
            <div>
              {stats.warning > 0 && <div>• {stats.warning}个证书即将过期，建议及时续期</div>}
              {stats.expired > 0 && <div>• {stats.expired}个证书已过期，请立即处理</div>}
              {stats.error > 0 && <div>• {stats.error}个证书监控异常，请检查配置</div>}
            </div>
          }
          type="warning"
          showIcon
          style={{ marginBottom: '24px' }}
          action={
            <Button size="small" type="primary">
              批量处理
            </Button>
          }
        />
      )}

      {/* 监控列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={monitorData}
          rowKey="id"
          pagination={{
            total: monitorData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>
    </div>
  );
};

export default CertificateMonitor; 